<template>
  <v-sheet
    class="bg-deep-purple fill-height d-flex flex-column justify-center align-center"
    rounded
  >
  <div>
    <v-row class="justify-center">
      <v-img
        src="@/assets/logo.png"
        max-width="320"
        class="mb-8"
      ></v-img>
    </v-row>
    <v-card
      class="mx-auto px-6 py-8 mt-24"
      max-width="540"
      min-width="340"
    >
      <v-form @submit.prevent="handleLogin">
        <v-text-field
          v-model="username"
          :readonly="loading"
          :rules="[required]"
          class="mb-2"
          label="学号"
          clearable
        ></v-text-field>

        <v-text-field
          v-model="password"
          :readonly="loading"
          :rules="[required]"
          label="密码"
          placeholder="Enter your password"
          :append-inner-icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'"
          @click:append-inner="showPassword = !showPassword"
          :type="showPassword ? 'text' : 'password'"
        ></v-text-field>

        <v-alert
          v-if="errorMessage"
          type="error"
          density="compact"
          variant="tonal"
          class="mb-4"
          closable
          @click:close="clearError"
        >
          {{ errorMessage }}
        </v-alert>
        <v-sheet v-else>
          <br />
        </v-sheet>

        <v-btn
          :loading="loading"
          color="success"
          size="large"
          type="submit"
          variant="elevated"
          block
        >
          登 录
        </v-btn>
      </v-form>
    </v-card>
  </div>
  </v-sheet>
</template>

<script lang="ts" setup>
  import { ref } from "vue";
  import { useRouter, useRoute } from "vue-router";
  import { useAuthStore } from "../stores/auth";

  const router = useRouter();
  const route = useRoute();
  const authStore = useAuthStore();

  const username = ref("");
  const password = ref("");

  const loading = ref(false);
  const showPassword = ref(false);

  const errorMessage = ref<string | null>(null);

  function required(v) {
    return !!v || "信息不能为空";
  }

  const clearError = () => {
    errorMessage.value = null;
  };

  const handleLogin = async () => {
    if (!username.value || !password.value) return;
    loading.value = true;
    try {
      await authStore.login(username.value, password.value);
      const redirect = (route.query.redirect as string) || "/";
      // console.log(redirect);
      router.push(redirect);
    } catch (error) {
      console.error("登录失败:", error);
      if (error.response && error.response.data.message) {
        errorMessage.value = error.response.data.message;
      } else {
        errorMessage.value = "登录失败！请稍后尝试";
      }
    } finally {
      loading.value = false;
    }
  };
</script>
